<template>
  <view class="comment">
    <!-- 评论列表 -->
    <view class="comments">
      <view class="title gohere" id="gohere" ref="gohere">最新评论</view>
      <view class="no-comment" v-if="commintsList.length == 0">暂无评论</view>
      <view
        v-for="(commentItem, index) in commintsList"
        :key="commentItem.id"
        class="one-comment"
      >
        <!-- 一级评论相关 -->
        <view class="commenter">
          <view class="info">
            <view class="left">
              <u-avatar
                size="50"
                class="avatar"
                :src="commentItem.userAvatar || ''"
              />
              <view class="name">{{ commentItem.userName }}</view>
            </view>
          </view>
          <u-read-more
            ref="uReadMore"
            show-height="200"
            :toggle="true"
            close-text="查看完整评论"
            color="#F2AE27"
          >
            <view class="content">{{ commentItem.content }}</view>
          </u-read-more>
          <view class="uptime"
            >{{
              (commentItem.updatedAt
                ? commentItem.updatedAt
                : commentItem.createdAt) | date('yyyy年mm月dd日 hh时MM分')
            }}
            评论</view
          >
        </view>
      </view>
    </view>

    <!-- 底部信息 -->
    <view class="tab-bar">
      <view class="minput" @tap="openComment">说点什么···</view>
      <view class="mview">
        <!-- 点赞相关统计 -->
        <view class="mbtn" @tap="sendLove">
          <image class="micon" :src="getLikeState" mode="aspectFit" />
          <text class="mtext">赞</text>
        </view>

        <view class="mbtn" @tap="sendInterstAuthor">
          <image class="micon" :src="getInterstState" mode="aspectFit" />
          <text class="mtext">关注作者</text>
        </view>

        <!-- 评论相关统计 -->
        <view class="mbtn" @tap="gotoComment">
          <image class="micon" src="/static/msg.png" mode="aspectFit" />
          <text class="mtext">评论</text>
        </view>
      </view>
    </view>

    <!-- 发布评论 -->
    <view class="commentBox" v-if="showCommentBox">
      <view class="header">
        <text class="title">发表评论</text>
        <u-icon
          class="icon"
          name="arrow-down-fill"
          color="#999"
          size="28"
          @tap="closeComment"
        />
      </view>
      <textarea
        class="texta"
        placeholder-style="color:#888"
        placeholder="想说点什么..."
        cursor-spacing="150"
        :focus="true"
        :fixed="true"
        :value="cinput"
        @input="getInput"
      />
      <view class="btns">
        <u-button
          size="mini"
          type="warning"
          :custom-style="sendBtnStyle"
          @click="sendComment"
          :disabled="disableSendCommentTag"
        >
          发布
        </u-button>

        <u-button
          size="mini"
          type="default"
          :custom-style="closeBtnStyle"
          @click="closeComment"
          :disabled="disableSendCommentTag"
        >
          取消
        </u-button>
      </view>
    </view>

    <!-- 登陆组件 -->
    <u-modal
      v-model="showLogin"
      :show-title="false"
      :show-confirm-button="false"
      :show-cancel-button="true"
      cancel-text="关闭"
    >
      <view>
        <login @loginStateChange="loginStateChange"></login>
      </view>
    </u-modal>
  </view>
</template>

<script>
import { mapState } from 'vuex';

export default {
  props: {
    Info: Object,
  },
  data() {
    return {
      closeBtnStyle: {
        marginLeft: '40rpx',
        width: '120rpx',
        height: '60rpx',
      },
      sendBtnStyle: {
        color: '#fff',
        backgroundColor: '#F2AE27',
        width: '120rpx',
        height: '60rpx',
      },
      // 当前动态评论列表详情
      commintsList: [],
      // props 传递的数据无法改变触发 DOM 更新 这里克隆一份
      // oneInfoClone: [],
      // 是否展开评论弹窗
      showCommentBox: false,
      // 评论输入内容
      cinput: '',
      // 是否可以发送评论
      disableSendCommentTag: true,
      //	控制是否显示登录组件
      showLogin: false,
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.userInfo.userInfo, //	用户信息
    }),
    // 计算用户对于这条博客的点赞状态  返回不同状态下的图标src
    getLikeState() {
      //	博客点赞的数量为0时
      if (!this.Info.like_count) {
        return '/static/love.png';
      }

      if (this.userInfo) {
        // 用户信息存在
        let inLikeList = this.Info.LikeBlogs.some((item) => {
          return item.likeUserId == this.userInfo.id;
        });
        return inLikeList ? '/static/lover.png' : '/static/love.png';
      } else {
        // 用户信息不存在
        return '/static/love.png';
      }
    },
    // 计算用户对于该作者的关注状态  返回不同状态下的图标src
    getInterstState() {
      //	博客点赞的数量为0时
      if (!this.Info.follow.count) {
        return '/static/weiguanzhu.png';
      }

      if (this.userInfo) {
        // 用户信息存在
        let inLikeList = this.Info.follow.rows.some((item) => {
          return item.followUserId == this.userInfo.id;
        });
        return inLikeList ? '/static/yiguanzhu.png' : '/static/weiguanzhu.png';
      } else {
        // 用户信息不存在
        return '/static/weiguanzhu.png';
      }
    },
  },
  async created() {
    this.getCommentsList();
  },
  mounted() {},
  methods: {
    // 获取评论列表
    async getCommentsList() {
      let commentRes = await this._api.getCommentByBlogId({
        blogId: this.Info.id,
      });

      this.commintsList = commentRes.rows;
    },
    //	获取用户对该条博客是否有点赞
    getHasLike() {
      let userLikeStatus;
      if (!this.Info.like_count) {
        // 文章的点赞数量为0时
        return (userLikeStatus = false);
      }

      let inLikeList = this.Info.LikeBlogs.some((item) => {
        return item.likeUserId == this.userInfo.id;
      });
      return (userLikeStatus = inLikeList ? true : false);
    },
    // 获取用户对该博客的作者是否关注
    getHasInterst() {
      let userInterstStatus;
      /* 博客作者被关注的数量为0时 关注状态为false*/
      if (!this.Info.follow.count) {
        return (userInterstStatus = false);
      }
      /* 查询博客作者被关注的用户id列表 存在本用户的id 为true */
      let inInterstAuthorList = this.Info.follow.rows.some((item) => {
        return item.followUserId == this.userInfo.id;
      });
      return (userInterstStatus = inInterstAuthorList ? true : false);
    },
    // 	登录组件状态更改事件
    loginStateChange(state) {
      // 登录状态变更为已登录了
      state && (this.showLogin = false);
    },
    // 发送点赞/取消赞博客请求
    async postLikeBlog(sucMsg, errMsg, type) {
      try {
        let res = await this._api.cancelLikeBlog({
          id: this.Info.id,
          projectId: 181,
        });
		//console.log(res)
        /* 向父组件暴露 点赞状态更改 
						type 1 增加点赞数
							 0 减少点赞数
					 */
        this.$emit('blogLikeChange', type);
        uni.showToast({
          title: sucMsg,
          icon: 'success',
          duration: 1000,
        });
      } catch (e) {
        uni.showToast({
          title: errMsg,
          icon: 'error',
          duration: 1000,
        });
      }
    },
    // 发送关注/取消关注 请求
    async postInterstAuthor(sucMsg, errMsg, type) {
      try {
		  //console.log(this.Info.userId)
      let res = await this._api.InterstAuthor({
          id: this.Info.userId, // 作者id
          projectId: 6,  //问题在于这里
        });
        /* 向父组件暴露 关注状态更改
						type 1 增加关注数
							 0 减少关注数
					 */
        this.$emit('authorInterstChange', type);
		//console.log(res)
        uni.showToast({
          title: sucMsg,
          icon: 'success',
          duration: 1000,
        });
      } catch (e) {
        uni.showToast({
          title: errMsg,
          icon: 'error',
          duration: 1000,
        });
      }
    },
    // 点赞逻辑操作
    async sendLove() {
      // 判断当前登录状态
      if (!(this.userInfo && this.userInfo.token)) {
        // 未登录 显示登录组件
        return (this.showLogin = true);
      }

      /*
					原本点赞数>0
					判断用户是否已经点赞 如果点赞了 执行取消点赞 否则执行点赞
				*/
      let hasLike = this.getHasLike();
      if (hasLike) {
        // 发送取消点赞请求
        this.postLikeBlog('消赞成功', '消赞失败', 0);
      } else {
        // 发送点赞请求
        this.postLikeBlog('点赞成功', '点赞失败', 1);
      }
    },
    // 关注逻辑操作
    async sendInterstAuthor() {
      // 判断当前登录状态
      if (!(this.userInfo && this.userInfo.token)) {
        // 未登录 显示登录组件
        return (this.showLogin = true);
      }

      /* 
					判断用户是否关注了该作者 如果关注了 执行取消关注 否则执行关注
				 */
      let hasInterst = this.getHasInterst();
      if (hasInterst) {
        // 发送取消关注请求
        this.postInterstAuthor('取消关注成功', '取消关注失败', 0);
      } else {
        // 发送关注请求
        this.postInterstAuthor('关注成功', '关注失败', 1);
      }
    },
    // 跳转到评论列表
    gotoComment() {
      const query = uni.createSelectorQuery().in(this);
      query
        .select('#gohere')
        .boundingClientRect((data) => {
          uni.pageScrollTo({
            duration: 500,
            scrollTop: data.top,
          });
        })
        .exec();
    },
    // 打开评论弹窗
    openComment() {
      // 判断当前登录状态
      if (!(this.userInfo && this.userInfo.token)) {
        // 未登录 显示登录组件
        return (this.showLogin = true);
      }
      this.showCommentBox = true;
    },
    closeComment() {
      this.showCommentBox = false;
    },
    // 获取输入内容
    getInput(e) {
      this.cinput = e.detail.value;
      if (!this.cinput) {
        this.disableSendCommentTag = true;
      } else {
        this.disableSendCommentTag = false;
      }
    },
    // 在这里设计 敏感词 鉴定操作
    doMsgSecCheck(text) {
      return wx.serviceMarket.invokeService({
        service: 'wxc77b7d95089201b3',
        api: 'msgSecCheck',
        data: {
          Action: 'TextApproval',
          Text: text,
        },
      });
    },
    // 发送评论信息
    // 	发送评论
    async sendComment() {
      // 发送状态判定
      if (this.disableSendCommentTag) return;
      this.disableSendCommentTag = true;

      // // #ifdef MP-WEIXIN
      // // 敏感词信息判定
      // let cres = await this.doMsgSecCheck(this.cinput)
      // console.log(cres);
      // if(cres.data.Response.EvilTokens.length > 0){
      // 	uni.showModal({
      // 		title:'敏感词审核',
      // 		content: '您发布的评论涉及敏感词：'+ cres.data.Response.EvilTokens[0].EvilKeywords
      // 	})
      // 	return
      // }
      // // #endif

      try {
        // 发送评论请求
        let commentRes = await this._api.commentBlog({
          blogId: this.Info.id,
          projectId: 181,
          content: this.cinput,
        });
        uni.showToast({
          title: '评论成功',
          icon: 'success',
          duration: 1000,
        });
        // 清空文本域
        this.cinput = '';
        //	关闭评论框
        this.closeComment();
        // 重新获取评论列表数据
        this.getCommentsList();
      } catch (e) {
        uni.showToast({
          title: e.msg,
          icon: 'error',
          duration: 1000,
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.comments {
  padding: 20upx 20upx 200upx;

  .title {
    font-weight: bolder;
    font-size: 32upx;
    margin-bottom: 40upx;
  }

  .no-comment {
    text-align: center;
    margin: 120upx 0 280upx;
    color: #666;
  }

  .one-comment {
    &.last-comment {
      border-bottom: none;
    }

    .commenter {
      .info {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        justify-content: space-between;
        align-items: center;
        align-content: center;
        margin-top: 20upx;

        .left {
          display: flex;
          flex-direction: row;
          flex-wrap: wrap;
          justify-content: flex-start;
          align-items: center;
          align-content: center;

          .avatar {
            margin-right: 20upx;
            margin-top: 10upx;
          }

          .name {
            font-size: 24upx;
            font-weight: bolder;
            color: #1f2046;
          }
        }
      }

      .content {
        color: #666;
        font-size: 30upx;
        line-height: 50upx;
        margin-left: 70upx;
        margin-top: 10upx;
        padding-right: 20upx;
      }

      .uptime {
        color: #999;
        font-size: 20upx;
        margin-left: 70upx;
        margin-top: 10upx;
        padding-bottom: 20upx;
        border-bottom: 1upx solid #f2f2f2;
      }
    }
  }
}

.tab-bar {
  position: fixed;
  width: 750upx;
  z-index: 20;
  height: 120upx;
  left: 0;
  bottom: 0;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  align-content: center;
  color: #ccc;
  border-top: 1upx solid #f6f6f6;
  background-color: #fff;

  .minput {
    background-color: #eee;
    height: 60upx;
    // #ifdef MP-WEIXIN
    width: 300upx;
    // #endif
    // #ifndef MP-WEIXIN
    width: 300upx;
    // #endif
    border-radius: 30upx;
    padding-left: 30upx;
    margin-left: 20upx;
    line-height: 60upx;
    color: #aaaaaa;
    font-size: 22upx;
  }

  .mview {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-evenly;
    align-items: center;
    align-content: center;
    color: #ccc;
    margin-right: 25upx;

    .mbtn {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: center;
      align-items: center;
      align-content: center;
      // width: 120upx;
      background-color: #fff;
      font-size: 18rpx;
      margin-right: 16rpx;
    }

    .mbtn::after {
      border: none;
      background-color: none;
    }

    .micon {
      width: 36upx;
      height: 36upx;
    }

    .mtext {
      color: #001432;
      font-size: 24upx;
      margin-left: 10upx;
    }
  }
}

.commentBox {
  position: fixed;
  width: 750upx;
  height: 250px;
  left: 0;
  bottom: 0;
  z-index: 20;
  border-top: 1upx solid #eee;
  background-color: #fafafa;

  .header {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: center;
    align-content: center;
    padding: 20upx 15px 20upx 25px;

    .title {
      color: #999;
      font-size: 28upx;
      font-weight: bold;
    }

    .icon {
      padding: 20upx;
    }
  }

  .texta {
    width: 600upx;
    height: 100px;
    margin-left: 50upx;
    padding: 10px 25upx;
    border: 1upx solid #ddd;
    border-radius: 10upx;
    background: #fff;
    font-size: 28upx;
  }

  .btns {
    width: 650upx;
    margin-left: 50upx;
    margin-top: 15px;
    text-align: right;

    .mini-btn {
      margin-left: 40upx;
    }
  }
}
</style>
